<template>
  <el-container>
    <el-header>
      <NavigationBar />
      <SearchMerchantBox />
    </el-header>

    <el-main>
      <el-row>
        <el-col :span="19">
          <el-card class="result-card">
            <!-- 查看商户简略信息 -->
            <div v-if="currentView === 'brief' && merchantBriefInfo">
              <h3>{{ merchantBriefInfo.merchant_name }}</h3>
              <p>商家ID: {{ merchantBriefInfo.merchant_ID }}</p>
              <h4>招牌菜:</h4>
              <ul>
                <li v-for="dish in merchantBriefInfo.signatureDish" :key="dish.dish_ID">{{ dish.dish_name }}</li>
              </ul>
            </div>
            <!-- 查看商户详细信息 -->
            <div v-else-if="currentView === 'detail' && merchantDetailInfo">
              <h3>{{ merchantDetailInfo.merchant_name }}</h3>
              <p>商家地址: {{ merchantDetailInfo.address }}</p>
            </div>
            <!-- 查看商户评价 -->
            <div v-else-if="currentView === 'ratings' && merchantRatings">
              <h3>商户评价</h3>
              <ul>
                <li v-for="rating in merchantRatings" :key="rating.merchant_review_ID">
                  <p>{{ rating.comment }}</p>
                  <p>评分: {{ rating.rating  }}</p>
                </li>
              </ul>
            </div>
            <!-- 查看菜单 -->
            <div v-else-if="currentView === 'menu' && merchantMenu">
              <h3>菜单</h3>
              <el-input v-model="searchDishQuery" placeholder="搜索菜品"></el-input> <!-- 添加搜索框 -->
              <el-table :data="filteredMenu" height="400"> <!-- 将表格数据绑定到过滤后的菜单 -->
                <el-table-column prop="dish_name" label="菜品名称" ></el-table-column>
                <el-table-column prop="price" label="价格"></el-table-column>
                <el-table-column prop="starNum" label="收藏量"></el-table-column>
                <el-table-column prop="salesVolume_online" label="线上销量"></el-table-column>
                <el-table-column prop="salesVolume_offline" label="排队销量"></el-table-column>
                <el-table-column width="400">
                  <template #default="scope">
                    <el-button type="info" @click="viewDishDetails(scope.row)">查看详情</el-button>
                    <el-button @click="addToOrder(scope.row)" type="success">加入订单</el-button>
                    <el-button @click="starDish(scope.row)" type="primary">收藏</el-button>
                    <el-button @click="cancelStarDish(scope.row)" type="primary">取消收藏</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-card>
        </el-col>

        <el-col :span="5">
          <el-card class="order-container">
            <el-table :data="OrderDetail" height="420">
              <el-table-column prop="name" label="菜品"></el-table-column>
              <el-table-column prop="quantity" label="数量"></el-table-column>
            </el-table>

            <el-button type="primary" @click="placeOrder(1)">在线下单</el-button> <!-- 添加参数1表示在线点餐 -->
            <el-button type="primary" @click="placeOrder(0)">排队点餐</el-button> <!-- 添加参数0表示排队点餐 -->
            <el-button type="warning" @click="clearOrder">清空</el-button>
          </el-card>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-card class="search-option">
            <div class="button-container">
              <el-button @click="reserveRestaurant" type="success" round>预定餐厅</el-button>
              <el-button @click="cancelStarMerchant" type="warning" round>取消收藏</el-button>
              <el-button @click="starMerchant" type="danger" round>收藏</el-button>
              <el-button @click="viewDetailInfo" round>查看商户地址</el-button>
              <el-button @click="viewAllDishes" round>查看菜单</el-button>
              <el-button @click="viewBriefInfo" round>查看商户简略信息</el-button>
              <el-button @click="viewRatings" round>查看商户评价</el-button>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-main>

    <!-- 预定时间输入框的模态框 -->
    <el-dialog title="预定餐厅" v-model="isReserveDialogVisible">
      <el-form>
        <el-form-item label="预定时间">
          <el-date-picker
            v-model="reserveTime"
            type="datetime"
            placeholder="选择日期和时间"
            format="YYYY-MM-DD HH:mm"
            value-format="YYYY-MM-DD HH:mm"
            :picker-options="{
              disabledDate(time) {
                return time.getTime() < Date.now();
              }
            }">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isReserveDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmReserve">确认</el-button>
      </div>
    </el-dialog>

  </el-container>
</template>

<script>
import axios from '@/axios'
import { mapState } from 'vuex'; // 引入 Vuex 的 mapState 函数, 访问 Vuex store 中的数据
import NavigationBar from '@/components/NavigationBar.vue';
import SearchMerchantBox from '@/components/SearchMerchantBox.vue';

export default {
  components: {
    NavigationBar,
    SearchMerchantBox
  },
  data() {
    return {
      searchQuery: '', // 保存用户的搜索查询字符串
      currentView: 'brief', // 当前显示的视图 brief: 商户简略信息, detail: 商户详细信息, ratings: 商户评价 menu: 商户菜单
      merchantBriefInfo: null, // 商户简略信息数据
      merchantDetailInfo: null, // 商户详细信息数据
      merchantRatings: null, // 商户评价数据
      merchantMenu: [], // 商户菜单数据，初始化为空数组
      merchant_ID: null, // 初始化商户ID
      OrderDetail: [], // 订单详情
      searchDishQuery: '', // 保存搜索字符串(搜索菜品)
      isReserveDialogVisible: false,  // 是否显示预定对话框
      reserveTime: '', // 预定时间
    }
  },
  computed: {
    ...mapState({
      user_ID: state => state.user.id,  // 将 Vuex store 中的 user_ID 状态映射为计算属性 user_ID，这样可以在组件中直接使用 this.user_ID
    }),
    filteredMenu() { // 根据搜索字符串过滤菜单
      if (this.merchantMenu) {
        return this.merchantMenu.filter(dish => dish.dish_name.includes(this.searchDishQuery));
      }
      return [];
    }
  },
  created() {
    this.merchant_ID = this.$route.params.id; // 从路由参数中获取商户ID
    this.viewBriefInfo(); // 获取商户简略信息
  },
  methods: {
    /* 查看商户简略信息 */
    async viewBriefInfo() {
      this.currentView = 'brief'; // 设置当前视图为商户简略信息
      try {
        const response = await axios.get(`/api/user/MerchantBrief/${this.merchant_ID}`); // 通过axios发送GET请求，获取商户简略信息数据
        this.merchantBriefInfo = response.data; // 更新数据状态，绑定到展示区域
      } catch (error) {
        this.$message.error('获取商户简略信息失败');
      }
    },
    /* 查看商户详细信息 */
    async viewDetailInfo() {
      this.currentView = 'detail';
      try {
        const response = await axios.get(`/api/user/MerchantDetail/${this.merchant_ID}`); // 通过axios发送GET请求，获取商户详情数据
        this.merchantDetailInfo = response.data; // 更新数据状态，绑定到展示区域
      } catch (error) {
        this.$message.error('获取商户详情失败');
      }
    },
    /* 收藏商家 */
    async starMerchant() {
      try {
        const starData = {
          user_ID: this.user_ID, // 从 Vuex store 中获取用户ID
          merchant_ID: this.merchant_ID // 从 data 中获取商户ID
        };

        const response = await axios.post('/api/user/UserStarMerchant', starData); // 通过axios发送POST请求，将收藏数据发送到后端API
        if (response.data.exists) { 
          this.$message.error('已收藏'); // 使用Element Plus的消息提示组件提示用户
        } else {
          this.$message.success('收藏成功');
        }
      } catch (error) {
        this.$message.error('收藏失败');
      }
    },
    /* 取消收藏商家 */
    async cancelStarMerchant() {
      try {
        const starData = {
          user_ID: this.user_ID, // 从 Vuex store 中获取用户ID
          merchant_ID: this.merchant_ID // 从 data 中获取商户ID
        };

        const response = await axios.post('/api/user/CancelStarMerchant', starData); // 通过axios发送POST请求，将取消收藏数据发送到后端API
        if (response.data.exists) { 
          this.$message.success('取消收藏成功'); // 使用Element Plus的消息提示组件提示用户
        } else {
          this.$message.error('未收藏');
        }
      } catch (error) {
        this.$message.error('取消收藏失败');
      }
    },
    /* 收藏菜品 */
    async starDish(dish) {
      try {
        const favoriteData = {
          user_ID: this.user_ID, // 从 Vuex store 中获取用户ID
          dish_ID: dish.dish_ID, // 从参数中获取菜品ID
          merchant_ID: this.merchant_ID // 从 data 中获取商户ID
        };

        const response = await axios.post('/api/user/StarDish', favoriteData); // 通过axios发送POST请求，将收藏数据发送到后端API
        if (response.data.exists) { 
          this.$message.error('已收藏'); // 使用Element Plus的消息提示组件提示用户
        } else {
          this.$message.success('收藏成功');
        }
      } catch (error) {
        this.$message.error('收藏菜品失败');
      }
    },
    /* 取消收藏菜品 */
    async cancelStarDish(dish) {
      try {
        const favoriteData = {
          user_ID: this.user_ID, // 从 Vuex store 中获取用户ID
          dish_ID: dish.dish_ID, // 从参数中获取菜品ID
          merchant_ID: this.merchant_ID // 从 data 中获取商户ID
        };

        const response = await axios.post('/api/user/CancelStarDish', favoriteData); // 通过axios发送POST请求，将取消收藏数据发送到后端API
        if (response.data.exists) { 
          this.$message.success('取消收藏成功'); // 使用Element Plus的消息提示组件提示用户
        } else {
          this.$message.error('未收藏');
        }
      } catch (error) {
        this.$message.error('取消收藏菜品失败');
      }
    },
    /* 查看菜单 */
    async viewAllDishes() {
      this.currentView = 'menu'; // 设置当前视图为商户菜单
      try {
        const response = await axios.get(`/api/user/UserGetMenu/${this.merchant_ID}`); // 通过axios发送GET请求，获取商户菜单数据
        this.merchantMenu = response.data; // 更新数据状态，绑定到展示区域
      } catch (error) {
        console.error('获取商户菜单失败', error);
        this.$message.error('获取商户菜单失败');
      }
    },
    /* 查看商户评价 */
    async viewRatings() {
        this.currentView = 'ratings';
        try {
          const response = await axios.get(`/api/user/UserGetMerchantRating/${this.merchant_ID}`); // 通过axios发送GET请求，获取商户评价数据
          console.log(response.data);
          this.merchantRatings = response.data; // 更新数据状态，绑定到展示区域
        } catch (error) {
          this.$message.error('获取商户评价失败');
        }
    },
    /* 将菜品加入订单 */
    addToOrder(dish) {
      const existingDish = this.OrderDetail.find(item => item.name === dish.dish_name);
      if (existingDish) {
        existingDish.quantity += 1; // 如果订单中已经有这个菜品，那么数量+1
      } else {
        this.OrderDetail.push({  
          id: dish.dish_ID, 
          quantity: 1, // 默认数量为1
          name: dish.dish_name
        });
      }
      this.$message.success('加入订单成功');
    },
    /* 下单 */
    async placeOrder(orderForm) { // 接受一个参数 orderForm 来区分在线点餐和排队点餐
      if (this.OrderDetail.length === 0) {
        this.$message.error('订单为空');
        return;
      }

      const orderData = this.OrderDetail.map(item => ({   // 将OrderDetail数组中的数据转换为后端需要的格式
        dish_ID: item.id,
        quantity: item.quantity
      })); 
      
      const orderPayload = {
        merchant_ID: this.merchant_ID, 
        user_ID: this.user_ID, 
        orderData: orderData, // 订单详细信息
        order_form: orderForm // 根据传入的参数设置 order_form
      };

      try {
        const response = await axios.post(`/api/user/placeOrder/${this.merchant_ID}`, orderPayload);
        this.$message.success('下单成功');
      } catch (error) {
        this.$message.error('下单失败');
      }
    },
    /* 清空订单 */
    clearOrder() {
        this.OrderDetail = []; 
        this.$message.success('订单已清空');
    },
    /* 显示预定餐厅时间输入框 */
    reserveRestaurant() {
      console.log(this.user_ID);
      this.isReserveDialogVisible = true; // 显示模态框
    },
    /* 确认预定餐厅 */
    async confirmReserve() {
      const orderData = {
        merchant_ID: this.merchant_ID,
        user_ID: this.user_ID,
        reserve_time: this.reserveTime // 获取用户输入的预定时间
      };
      try {
        const response = await axios.post('/api/user/Reserve', orderData);
        this.$message.success('预定成功');
        this.isReserveDialogVisible = false; // 隐藏模态框
      } catch (error) {
        this.$message.error('预定失败');
      }
    },
    /* 查看菜品详细信息 */
    viewDishDetails(dish) {
      this.$router.push(`/dish_detail/${dish.dish_ID}`);
    }
    }
}
</script>

<style scoped>
.order-container {
  height: 500px; /* 设置订单展示区域的高度 */
  margin-bottom: 10px;
}
.result-card {
  height: 500px; /* 设置查询结果展示卡片的高度 */
  margin-bottom: 10px;
}
.search-option {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 100px; 
}
.button-container {
    display: flex;
    flex-direction: row;  
    gap: 10px; /* 设置按钮之间的间距 */
    width: 100%; 
    padding: 10px;
    box-sizing: border-box; 
}
.dish-detail {
  font-size: small;
}
</style>
  